package com.budweiser.user.controller;

import com.budweiser.commons.utils.Utils;
import com.budweiser.model.log.LogAnnotation;
import com.budweiser.model.organ.Organization;
import com.budweiser.model.result.ResponseBase;
import com.budweiser.model.result.ResultBase;
import com.budweiser.user.dto.OrganSelectTree;
import com.budweiser.user.dto.OrganizationTree;
import com.budweiser.user.service.OrganizationService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class OrganizationController {
	@Autowired
	private OrganizationService organizationService;

	@GetMapping("/orgin/all")
	public ResultBase<OrganizationTree> getMenuByAll() {
		return new ResultBase<OrganizationTree>(0, "加载成功！", 0, organizationService.getOrganizationByAll());
	}

	@GetMapping("/orgin/selectOrginTree")
	public List<OrganSelectTree> selectMenuTree() {
		List<OrganSelectTree> organSelectTrees = organizationService.getOrganSelectTrees();
		List<OrganSelectTree> firstorganSelectTrees = organSelectTrees.stream().filter(m -> m.getPid().equals(0l))
				.collect(Collectors.toList());
		firstorganSelectTrees.forEach(select -> {
			setChildSelectTree(select, organSelectTrees);
		});
		return firstorganSelectTrees;
	}

	public void setChildSelectTree(OrganSelectTree organSelectTree, List<OrganSelectTree> organSelectTrees) {
		List<OrganSelectTree> child = organSelectTrees.stream().filter(m -> m.getPid().equals(organSelectTree.getId()))
				.collect(Collectors.toList());
		if (!CollectionUtils.isEmpty(child)) {
			organSelectTree.setChildren(child);
			child.parallelStream().forEach(s -> {
				setChildSelectTree(s, organSelectTrees);
			});
		}
	}

	@LogAnnotation(module = "新增机构")
	@PostMapping("/orgin/save")
	@PreAuthorize("hasAuthority('back:organ:save')")
	public ResponseBase save(Organization organization) {
		organizationService.save(organization);
		return new ResponseBase(200, "新增成功！", null);
	}

	@LogAnnotation(module = "修改机构")
	@PostMapping("/orgin/update")
	@PreAuthorize("hasAuthority('back:organ:update')")
	public ResponseBase update(Organization organization) {
		organizationService.update(organization);
		return new ResponseBase(200, "修改成功！", null);
	}

	@LogAnnotation(module = "刪除机构")
	@PostMapping("/orgin/delete")
	@PreAuthorize("hasAuthority('back:organ:delete')")
	public ResponseBase deleteIds(String ids) {
		organizationService.deleteIds(Utils.getLongs(ids));
		return new ResponseBase(200, "删除成功！", null);
	}

	@RequestMapping(value = "/orgins-anon/findOrganizationById", method = RequestMethod.POST)
	public Organization findOrganizationById(@RequestBody Long orgid) {
		return organizationService.findOrganizationById(orgid);
	}
}
